package com.skeleton.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.skeleton.db.dto.UserinfoDto;
import com.skeleton.utils.SystemConstants;

@Component
public class SystemInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LogManager.getLogger(this.getClass());

	String[] urls = { "/login", "/regist", "/user/ajaxLogin",  "/user/ajaxRegist", "/resource"};

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 当前请求路径
		String currentURI = request.getRequestURI().replace(request.getContextPath(), "").trim();
		// 不需要登陆的url

		logger.info("================================");
		logger.info("访问路径：" + currentURI);
		logger.info("================================");
//		logger.debug("================================");
//		logger.debug("访问路径：" + currentURI);
//		logger.debug("================================");

		boolean isAllow = false;
		for (int i = 0; i < urls.length; i++) {
			String url = urls[i];
			if (currentURI.startsWith(url)) {
				isAllow = true;
			}
		}
		if (!isAllow) {
			UserinfoDto ud = (UserinfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
			if (ud == null) {
				response.sendRedirect("/Ske/login");
				return false;
			} else {
				return super.preHandle(request, response, handler);
			}
		}

		return super.preHandle(request, response, handler);
	}

}
